﻿/// <reference path="json2.js" />
/// <reference path="XrmPage_vsdoc.js" />

if (typeof (EBL) === "undefined") {
    EBL = {};
}

EBL.FormHelper = function () {
    /****************** PRIVATE  *******************/
    var FORM_UNDEFINED = 0;
    var FORM_CREATE = 1;
    var FORM_UPDATE = 2;
    var FORM_READONLY = 3;
    var FORM_DISABLED = 4;
    var FORM_QUICKCREATE = 5;   //(Deprecated)
    var FORM_BULKEDIT = 6;
    var FORM_READOPTIMIZED = 11; // (Deprecated)

    var ODataPath = Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/";

    function toTitleCase(str) {
        return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
    }
    function getSource(context) {
        if (typeof (context) === 'undefined') {
            alert("You'll need to set the 'Pass execution conext as first parameter' in order for this to work.\n\nPlease contact your CRM Administrator/Developer for assistance.");
            return;
        }

        if (typeof (context.getEventSource) === 'undefined') {
            alert("You'll need to set the 'Pass execution conext as first parameter' in order for this to work.\n\nPlease contact your CRM Developer/Administrator for assistance.");
            return;
        }
        return context.getEventSource();
    }
    function errorHandler(error) {
        wrtieToConsole(error.message);
    }
    function writeToConsole(message){
        if (typeof (console) !== "undefined") {
            console.warn(message);
        }
    }
    function onRestError(xhr, status, errorThrown) {
        debugger;
        var msg = JSON.parse(xhr.responseText).error.message.value;
        writeToConsole(msg);
    }

    /******************** PUBLIC  *****************/
    /******************** PUBLIC  *****************/
    /******************** PUBLIC  *****************/
    return {
        DefaultFromUserRecord: function (fieldToDefault, defaultFromField) {    //"address1_stateorprovince", "Address1_StateOrProvince"
            "use strict";
            if (Xrm.Page.ui.getFormType() !== FORM_CREATE) {
                return;
            }

            if (typeof(fieldToDefault) === "undefined" || typeof (defaultFromField) === "undefined") {
                alert("DefaultFromUserRecord needs 2 arguments (fieldToDefault & defaultFromField).  Check your OnLoad Events");
                return;
            }

            if (typeof (JSON) === "undefined") {
                alert("DefaultFromUserRecord requires JSON2.js.  Check your Form Properties.");
                return;
            }

            var attribute = Xrm.Page.getAttribute(fieldToDefault.toLowerCase()); 
            if (!attribute) {
                alert("DefaultFromUserRecord Cannot find [" + fieldToDefault.toString() + "] on this page.  Check your OnLoad Events");
                return;
            }
            var value = attribute.getValue();
            if (value !== null) {
                return;
            }

            var userId = Xrm.Page.context.getUserId();
            var req = new XMLHttpRequest();
            req.open("GET", encodeURI(ODataPath + "SystemUserSet(guid'" + userId + "')?$select=" + defaultFromField), true);
            req.setRequestHeader("Accept", "application/json");
            req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            req.onreadystatechange = function () {
                if (this.readyState === 4 /* complete */) {
                    req.onreadystatechange = null;
                    if (this.status === 200) {
                        var data = JSON.parse(this.responseText);
                        var defaultValue = data.d[defaultFromField];

                        attribute.setSubmitMode('never');   // when we set the field CRM will think it's dirty.  this will prevent the tracking of isDirty, but CRM wont save it if it's not dirty, so to fix this we'll tell CRM to save this field in the OnSave event.
                        attribute.setValue(defaultValue);
                        Xrm.Page.data.entity.addOnSave(function () {
                            attribute.setSubmitMode('always');
                        });
                    }
                    else {
                        writeToConsole(this.statusText);
                    }
                }
            };
            req.send();

            //
            //CrmRestKit.Retrieve('SystemUser', userId, [defaultFromField]).then(function (data) {
            //    var defaultValue = data.d[defaultFromField];
            //    attribute.setValue(defaultValue);
            //}).fail(onRestError);
        },
        PhoneFormatAreaCode: function (context) {
            var src = getSource(context);
            var phone = src.getValue().toString();

            if (phone.substr(0, 1) === "+")
                return;

            phone = phone.replace(/[^0-9]/g, '');
            if (phone.length === 10) {
                phone = phone.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
                src.setValue(phone);
            }
            return;
        },
        PhoneFormat: function (context) {
            var src = getSource(context);
            var phone = src.getValue();

            if (phone.substr(0, 1) === "+")
                return;

            phone = phone.replace(/[^0-9]/g, '');
            if (phone.length === 10) {
                phone = phone.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
                src.setValue(phone);
            }

            return;
        },

        TitleCase: function (context, arg2) {
            "use strict";
            if (typeof (context) === 'undefined') {
                alert("You'll need to set the 'Pass execution conext as first parameter' in order for this to work.\n\nPlease contact your CRM Administrator/Developer for assistance.");
                return;
            }

            if (typeof (context.getEventSource) === 'undefined') {
                alert("You'll need to set the 'Pass execution conext as first parameter' in order for this to work.\n\nPlease contact your CRM Developer/Administrator for assistance.");
                return;
            }

            var src = context.getEventSource();

            var val = src.getValue();
            if (val === val.toUpperCase() || val === val.toLowerCase()) {
                var newVal = toTitleCase(val);
                src.setValue(newVal);
            }
        },

        PublicFunction: function (context) {
            "use strict";
            // code goes here
        }
    };

}();